<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html, body {
            height: 100%;
        }

        .chat-container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        .chat-history {
            border: 1px solid darkred;
            height: 800px;
            flex-grow: 1;
            overflow-y: auto;
        }
        .message {
            margin-bottom: 15px;
            display: flex;
        }
        .message-content {
            padding: 10px 15px;
            border-radius: 15px;
            max-width: 70%;
        }
        .user-message {
            justify-content: flex-end;
        }

        .ai-message {
            justify-content: flex-start;
        }
        .input-container {
            border: 1px solid darkgreen;
            padding: 1rem;
            display: flex;
            justify-content: space-between;
        }
        #message-input{
            flex-grow: 1;
            padding: 8px;
        }
        #send-button{
            margin-left: 8px;
            padding: 0 1rem;
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="chat-history" id="chat-history"></div>
    <div class="input-container">
        <input id="message-input" type="text" placeholder="请输入消息">
        <button id="send-button">发送</button>
    </div>
</div>

<script src="jquery.min.js"></script>
<script>
    const messageInput = document.getElementById("message-input");
    const sendButton = document.getElementById("send-button");
    const chatHistory = document.getElementById("chat-history");

    sendButton.addEventListener("click", send)
    messageInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
            send();
        }
    })

    function send(){
        const message = messageInput.value;
        if (message){
            addMessage(message);
            messageInput.value='';

            // 模拟 AI 的响应
            // setTimeout(() => {
            //     addMessage('来自 AI 的响应: ' + message, true);
            // }, 1000)
            // getResponseFromServer(message)
            getStreamResponse(message)
        }
    }

    function addMessage(content, isAI = false) {
        const messageDiv = document.createElement('div');
        // messageDiv.className = `message`;
        messageDiv.className = `message ${isAI ? 'ai-message' : 'user-message'}`;

        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        messageContent.textContent = content;

        messageDiv.appendChild(messageContent);
        chatHistory.appendChild(messageDiv);

        // 滚动到最新消息
        chatHistory.scrollTop = chatHistory.scrollHeight;

        return messageContent; // 返回消息内容元素，用于流式更新
    }

    function getResponseFromServer(message) {
        $.get("/ai/chat", {message: message}, function(resp) {
            addMessage(resp, true)
        });
    }

    function getStreamResponse(message) {
        // 创建AI消息占位符
        const aiMessageContent = addMessage('', true);

        // 创建EventSource连接
        const eventSource = new EventSource(`/ai/chat-stream?prompt=${encodeURIComponent(message)}`);

        // 用于累积接收到的内容
        let accumulatedContent = '';

        // 处理接收到的消息
        eventSource.onmessage = function(event) {
            accumulatedContent += event.data;
            aiMessageContent.textContent = accumulatedContent;
            chatHistory.scrollTop = chatHistory.scrollHeight;
        };

        // 处理错误
        eventSource.onerror = function(error) {
            eventSource.close();
            if (accumulatedContent === '') {
                aiMessageContent.textContent = '抱歉，发生错误了';
            }
        };
    }
</script>
</body>
</html>